package com.yvan.leto.listener;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.util.StatusPrinter;
import com.yvan.leto.ConfigChangeEvent;
import com.yvan.leto.ConfigListener;
import com.yvan.leto.SegmentHelper;
import lombok.Cleanup;
import lombok.SneakyThrows;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;

public class LogbackListener implements ConfigListener {

    @Override
    public String watchSegment() {
        return SegmentHelper.LOGBACK;
    }

    @Override
    @SneakyThrows
    public void onChange(ConfigChangeEvent changeEvent) {
        final String xmlContent = changeEvent.getChanges();
        @Cleanup ByteArrayInputStream inputStream = new ByteArrayInputStream(xmlContent.getBytes("utf-8"));
        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(lc);
        lc.reset();
        configurator.doConfigure(inputStream);
        StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
    }
}
